package com.itobase.questionnaire.service.impl;


import com.alibaba.fastjson.JSON;
import com.itobase.questionnaire.service.IFileService;
import com.itobase.questionnaire.util.Message;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author cong
 * @date 2018/7/29
 */
@Service
public class FileService implements IFileService {

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Override
    public String fileUpload(MultipartFile file) throws IOException {
        GridFSFile fsFile = gridFsTemplate.store(
                file.getInputStream(), file.getOriginalFilename(), file.getContentType());
        return fsFile.getId().toString();
    }

    @Override
    public void download(String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        GridFSDBFile fsFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));

        if (fsFile == null) {
            outputStream.write(JSON.toJSONBytes(Message.createErr("对不起， 该文件不存在")));
        }
        response.setHeader("Content-Type", fsFile.getContentType());
        String filename = fsFile.getFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));

        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);

        response.setHeader("type", suffix);
        fsFile.writeTo(outputStream);
        outputStream.close();
    }
}
